import { Service } from "@/middleware/response";
import { AdminUserModel } from "@/models/admin/User";
import { PageReq } from "@/types/common/common";
import {
    catchError,
    createRecord,
    deleteRecord,
    getPageList,
    GetPageListOptions,
    getRecord,
    updateRecord,
    GetRecordOptions,
    CreateRecordOptions,
    UpdateRecordOptions,
    DeleteRecordOptions,
} from "@/utils/db";
import { AdminUser } from "@/types/admin/auth";
import { setUserRolePermission } from "@/middleware/admin/auth";

export const getUserListService: Service = async (req, res) => {
    const { page, pageSize, ...match } = req.query;
    const { username, email, nickname } = match;
    const options: GetPageListOptions<AdminUser> = {
        model: AdminUserModel,
        params: req.query as PageReq,
    };
    if (username || email || nickname) options.$match = {};
    if (options.$match) {
        if (typeof username === "string") options.$match.username = { $regex: RegExp(username), $options: "i" };
        if (typeof email === "string") options.$match.email = { $regex: RegExp(email), $options: "i" };
        if (typeof nickname === "string") options.$match.nickname = { $regex: RegExp(nickname), $options: "i" };
    }
    catchError({
        async operation() {
            const { total, list } = await getPageList(options);
            res.sendResponse!(200, { total, list });
        },
        res,
        type: "查询",
    });
};
export const getUserDetailService: Service = async (req, res) => {
    const { _id } = req.params;
    const childFields:GetRecordOptions<AdminUser>['childFields'] = [];
    catchError({
        async operation() {
            return await getRecord({ model: AdminUserModel, _id, childFields });
        },
        res,
        type: "查询",
    });
};
export const createUserService: Service = async (req, res) => {
    const { ...data } = req.body;
    catchError({
        async operation() {
            const childFields:CreateRecordOptions<AdminUser>['childFields'] = [];
            await createRecord({ model: AdminUserModel, childFields, data });
        },
        res,
        type: "创建",
    });
};
export const updateUserService: Service = async (req, res) => {
    const { _id, ...data } = req.body;
    catchError({
        async operation() {
            await setUserRolePermission(req, res, true);
            const childFields:UpdateRecordOptions<AdminUser>['childFields'] = [];
            await updateRecord({ model: AdminUserModel, _id, childFields, data });
        },
        res,
        type: "更新",
    });
};
export const deleteUserService: Service = async (req, res) => {
    const { _id } = req.body;
    const childFields:DeleteRecordOptions<AdminUser>['childFields'] = [];
    catchError({
        async operation() {
            await deleteRecord({ model: AdminUserModel, _id, childFields });
        },
        res,
        type: "删除",
    });
};
